package baseproject.com.mybaseproject.utils.scheduler

import android.content.Context
import android.view.View
import baseproject.com.mybaseproject.utils.NetworkUtil
import baseproject.com.mybaseproject.utils.ToastUtils
import com.jakewharton.rxbinding2.view.RxView
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

object RxUtils {
    fun <T> io2main(): ObservableTransformer<T, T> {
        return ObservableTransformer { observable ->
            observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        }
    }
    fun <T> downloadFile(): ObservableTransformer<T, T> {
        return ObservableTransformer { observable ->
            observable.subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .observeOn(Schedulers.computation())
        }
    }

    /**
     * 需要判断网络时候的View的点击事件
     */
    fun rxClickOnCheckNet(context: Context , isLandScape : Boolean , clickView : View , onClickInterf: OnClickInterf){
        RxView.clicks(clickView)
                .throttleFirst(1000 , TimeUnit.MILLISECONDS)
                .subscribe(Consumer {
                    if (isLandScape){
                        if (!NetworkUtil.isNetworkAvailable(context)){
                            ToastUtils.showToast("无法连接网络")
                            return@Consumer
                        }
                    }
                    onClickInterf?.onViewClick(clickView)
                })
    }

    /**
     * Rx  View的点击事件
     */
    fun rxClick(clickView : View , onClickInterf: OnClickInterf){
        RxView.clicks(clickView)
                .throttleFirst(1000 , TimeUnit.MILLISECONDS)
                .subscribe(Consumer {
                    onClickInterf?.onViewClick(clickView)
                })
    }

    interface OnClickInterf{
        fun onViewClick(view : View)
    }
}